package mytools;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.socks.library.KLog;
import com.sxpjyy.monkey.mobilenurse.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class UpdateInfo {

    public static String getUpdateVerJSON(Context context) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ApplicationUtil.applicationContext);
        String serverAdd = sharedPreferences.getString("server_address", ApplicationUtil.applicationContext.getString(R.string.default_server));
        String serverPath = "http://" + serverAdd + File.separator + context.getResources().getString(R.string.version_json);
        return getVersionResult(serverPath);
    }

    public static boolean isServerAvailable(String serverAdd) {
        String serverPath = "http://" + serverAdd + "/version.json";
        return getVersionResult(serverPath) != null;
    }

    private static String getVersionResult(String serverPath) {
        try {
            StringBuilder newVerJSON = new StringBuilder();
            OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).build();
            Request request = new Request.Builder().url(serverPath).build();
            Response response;
            response = okHttpClient.newCall(request).execute();
            if (response.code() == 404) {
                return null;
            } else {
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody.byteStream(), "UTF-8"), 8192);
                    String line;
                    while ((line = reader.readLine()) != null) {  //按行读取文件
                        newVerJSON.append(line).append("\n");
                    }
                    reader.close();
                }
                return newVerJSON.toString();
            }
        } catch (Exception e) {
            KLog.d(e.getMessage());
            e.printStackTrace();
            return null;
        }

    }
}
